package me.magicall.test.db.spring;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.magicall.coll.ElementTransformerUtil;
import me.magicall.db.meta.DbColumn;
import me.magicall.db.meta.TableMeta;
import me.magicall.db.meta.TableMetaAccessor;
import me.magicall.db.util.DbUtil;
import me.magicall.util.kit.Kits;

import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class Dao1 {

	SimpleJdbcTemplate jdbc;
	TableMetaAccessor tableMetaBuilder;

	Person get(final Person smaller, final Person bigger) {
		//从dao的注解上获得表名
		final String tableName = null;
		//根据表名获得表的meta
		final TableMeta meta = tableMetaBuilder.getTableMetaUsingModelName(tableName);//FIXME:use field name

		//拼sql
		final StringBuilder sb = new StringBuilder("select ");
		final List<DbColumn> fields = meta.getColumns();

		//字段
		Kits.STR.join(sb, fields, ",", ElementTransformerUtil.TO_NAME);
		//表名
		sb.append(" from ").append(DbUtil.quoteDbName(tableName));

		//条件
		final List<String> fieldNames = Kits.LIST.transform(fields, ElementTransformerUtil.TO_NAME);
		final Map<String, Object> fieldValuesSmaller = fieldValues(smaller);
		final Map<String, Object> fieldValuesBigger = fieldValues(bigger);

		final List<String> conditions = new ArrayList<String>();
		for (final String fieldName : fieldNames) {
			final Object smallerValue = fieldValuesSmaller.get(fieldName);
			final Object biggerValue = fieldValuesBigger.get(fieldName);
			if (smallerValue == null) {
				if (biggerValue == null) {
					continue;
				} else {
					conditions.add(fieldName + "<=" + biggerValue);
				}
			}
			if (biggerValue == null) {
				conditions.add(fieldName + ">=" + smallerValue);
			} else if (smallerValue.equals(biggerValue)) {
				conditions.add(fieldName + "=" + biggerValue);
			} else {
				conditions.add(fieldName + "<=" + biggerValue);
				conditions.add(fieldName + ">=" + smallerValue);
			}
		}
		if (!conditions.isEmpty()) {
			sb.append(" where ");
			Kits.STR.join(sb, conditions, " and ");
		}
		//查询
		return null;
	}

	static Map<String, Object> fieldValues(final Object bean) {
		if (bean == null) {
			return Kits.MAP.emptyValue();
		}
		return null;
	}

}
